package me.tuyou.handler.server;

import me.tuyou.handler.UserHandler;
import me.tuyou.servcie.impl.UserServiceImpl;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.netty.http.server.HttpServer;

import java.io.IOException;

import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;

/**
 * 基于编程式的模式获取
 */
public class Server {
    /**
     * 创建路由
     * @return
     */
    public RouterFunction<ServerResponse> routerFunction(){
        // 创建处理器
        UserHandler userHandler=new UserHandler(new UserServiceImpl());
        return RouterFunctions.route().GET("/users/{id}",userHandler::getUserById)
                // 查询全部
                .GET("/alls",userHandler::getAllUser)
                // 单个添加
                .POST("/users/add",userHandler::saveUser)
                .build();

    }
    public void createReactorServer(){
        // 路由和handler适配
        RouterFunction<ServerResponse> routerFunction = this.routerFunction();
        HttpHandler httpHandler = toHttpHandler(routerFunction);
        ReactorHttpHandlerAdapter reactorHttpHandlerAdapter = new ReactorHttpHandlerAdapter(httpHandler);
        // 创建服务器
        HttpServer httpServer = HttpServer.create();
        httpServer.handle(reactorHttpHandlerAdapter).bindNow();
    }

    public static void main(String[] args) throws IOException {
        Server server=new Server();
        server.createReactorServer();
        System.out.println("enter to exit");
        System.in.read();
    }
}
